package main

import (
	"fmt"
	"strings"
	"strconv"
	"os/exec"
	"github.com/aws/aws-sdk-go/service/cloudwatch"
	"github.com/aws/aws-sdk-go/aws"
	"aws_sys_monitor/common"
)

const meminfo = "/proc/meminfo"
const loadavg = "/proc/loadavg"
const cpuinfo = "/proc/cpuinfo"

func getMemInfo() (memUsedPrice float64) {
	memMap := make(map[string]float64)

	f, err := common.ReadAll(meminfo)
	if err != nil {
		fmt.Printf("Unable to filepath, %v\n", err)
	}
	for _, line := range strings.Split((string(f)), "\n")[:4] {
		fields := strings.Fields(line)
		memFloat, _ := strconv.ParseFloat(fields[1], 1)
		memMap[strings.Trim(fields[0], ":")] = memFloat
	}

	memUsedPrice = ((memMap["MemTotal"] - memMap["MemFree"] - memMap["Buffers"] - memMap["Cached"] ) / memMap["MemTotal"]) * 100

	return
}

func getDiskUsed(mountPath string) (diskUsedPrice int) {
	cmd := exec.Command("/bin/df", "-k", "-l", "-P", mountPath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Printf("查询磁盘用量命令失败 %s\n", out)

	}
	for _, line := range strings.Split((string(out)), "\n")[1:2] {
		fields := strings.Fields(line)
		diskUsedPrice, _ = strconv.Atoi(strings.Trim(fields[4], "%"))
	}
	return diskUsedPrice
}

func getLoadAvg() (loadAvgPrice float64) {
	f, err := common.ReadAll(loadavg)
	if err != nil {
		fmt.Printf("Unable to filepath, %v\n", err)
	}
	fields := strings.Fields(string(f))
	priceFloat, _ := strconv.ParseFloat(fields[2], 64)
	loadAvgPrice = priceFloat * 100 / float64(cpuProcessor())

	return
}

func cpuProcessor() (processorNum int) {
	processorNum = 0
	f, err := common.ReadAll(cpuinfo)
	if err != nil {
		fmt.Printf("Unable to filepath, %v\n", err)
	}
	for _, line := range strings.Split((string(f)), "\n") {
		if strings.HasPrefix(line, "processor") {
			processorNum ++
		}
	}
	return
}



func main() {
	instanceId, _ := common.HttpGet()

	loadAverageData := &cloudwatch.MetricDatum{
		MetricName: aws.String("LoadAverage"),
		Unit:       aws.String("Percent"),
		Value:      aws.Float64(getLoadAvg()),
		Dimensions: []*cloudwatch.Dimension{
			{Name: aws.String("InstanceId"), Value: aws.String(instanceId)},
		},
	}

	common.MetricDataPut(loadAverageData,"System/Linux")

}
